#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试工作流数据
"""

import os
import sys
import json
from PIL import Image

# 添加当前目录到路径
current_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, current_dir)

def debug_workflow():
    """调试工作流数据"""
    image_path = os.path.join(current_dir, "1.png")
    
    try:
        print("=" * 80)
        print("调试工作流数据")
        print("=" * 80)
        
        with Image.open(image_path) as img:
            print(f"图片信息:")
            print(f"  尺寸: {img.size}")
            print(f"  模式: {img.mode}")
            print(f"  格式: {img.format}")
            
            if hasattr(img, 'info') and img.info:
                print(f"\nPNG元数据键: {list(img.info.keys())}")
                
                # 输出prompt数据
                if 'prompt' in img.info:
                    prompt_data = img.info['prompt']
                    print(f"\nPrompt数据:")
                    print(f"  类型: {type(prompt_data)}")
                    print(f"  长度: {len(str(prompt_data))}")
                    print(f"  内容: {str(prompt_data)[:200]}...")
                
                # 输出工作流数据
                if 'workflow' in img.info:
                    workflow_data = img.info['workflow']
                    print(f"\n工作流数据:")
                    print(f"  类型: {type(workflow_data)}")
                    print(f"  长度: {len(workflow_data)}")
                    print(f"  字符: {workflow_data}")
                    
                    # 解析JSON
                    try:
                        workflow_json = json.loads(workflow_data)
                        print(f"\n解析后的工作流:")
                        print(f"  根键: {list(workflow_json.keys())}")
                        
                        if 'nodes' in workflow_json:
                            nodes = workflow_json['nodes']
                            print(f"  节点类型: {type(nodes)}")
                            print(f"  节点数量: {len(nodes)}")
                            
                            if isinstance(nodes, list):
                                print(f"\n前10个节点:")
                                for i, node in enumerate(nodes[:10]):
                                    print(f"    节点 {i}:")
                                    print(f"      类型: {node.get('type', '未知')}")
                                    print(f"      class_type: {node.get('class_type', '未知')}")
                                    inputs = node.get('inputs', {})
                                    if isinstance(inputs, dict):
                                        print(f"      输入键: {list(inputs.keys())}")
                                    else:
                                        print(f"      输入类型: {type(inputs)}")
                                        print(f"      输入内容: {inputs}")
                                    
                                    # 检查是否有LoRA相关字段
                                    inputs = node.get('inputs', {})
                                    if isinstance(inputs, dict):
                                        lora_fields = [k for k in inputs.keys() if 'lora' in k.lower()]
                                        if lora_fields:
                                            print(f"      LoRA字段: {lora_fields}")
                                            for field in lora_fields:
                                                print(f"        {field}: {inputs[field]}")
                                    
                                    # 检查class_type是否包含LoRA
                                    class_type = node.get('class_type', '')
                                    if 'lora' in class_type.lower():
                                        print(f"      *** 这是LoRA节点! ***")
                                        print(f"      完整输入: {inputs}")
                                    
                                    # 检查widgets_values中的LoRA信息
                                    widgets_values = node.get('widgets_values', [])
                                    if isinstance(widgets_values, list):
                                        for i, widget in enumerate(widgets_values):
                                            if isinstance(widget, dict) and 'lora' in widget:
                                                print(f"      Widget {i}: LoRA = {widget.get('lora')}, 激活 = {widget.get('on')}, 强度 = {widget.get('strength')}")
                                
                                # 专门查找PowerLoraLoaderHeaderWidget节点
                                print(f"\n查找PowerLoraLoaderHeaderWidget节点:")
                                power_lora_nodes = []
                                for i, node in enumerate(nodes):
                                    inputs = node.get('inputs', {})
                                    if 'PowerLoraLoaderHeaderWidget' in inputs:
                                        power_lora_nodes.append((i, node))
                                        print(f"    找到PowerLoraLoaderHeaderWidget节点 {i}:")
                                        print(f"      完整输入: {inputs}")
                                
                                if power_lora_nodes:
                                    print(f"\n*** 找到 {len(power_lora_nodes)} 个PowerLoraLoaderHeaderWidget节点 ***")
                                    
                                    # 提取所有激活的LoRA
                                    all_loras = []
                                    for node_idx, node in power_lora_nodes:
                                        inputs = node.get('inputs', {})
                                        print(f"\n  节点 {node_idx} 的LoRA列表:")
                                        
                                        # 遍历所有可能的lora字段
                                        for key, value in inputs.items():
                                            if key.startswith('lora_') and isinstance(value, dict):
                                                lora_name = value.get('lora', '')
                                                is_on = value.get('on', False)
                                                strength = value.get('strength', 1.0)
                                                
                                                if lora_name:
                                                    print(f"    {key}: {lora_name} (激活: {is_on}, 强度: {strength})")
                                                    if is_on:
                                                        all_loras.append({
                                                            'name': lora_name,
                                                            'strength': strength,
                                                            'node_id': node_idx
                                                        })
                                    
                                    print(f"\n*** 激活的LoRA总数: {len(all_loras)} ***")
                                    for lora in all_loras:
                                        print(f"  - {lora['name']} (强度: {lora['strength']})")
                                else:
                                    print("  未找到PowerLoraLoaderHeaderWidget节点")
                                
                                # 保存完整工作流
                                output_file = os.path.join(current_dir, "scripts", "full_workflow.json")
                                with open(output_file, 'w', encoding='utf-8') as f:
                                    json.dump(workflow_json, f, ensure_ascii=False, indent=2)
                                print(f"\n完整工作流已保存到: {output_file}")
                                
                    except Exception as e:
                        print(f"解析工作流失败: {e}")
                        import traceback
                        traceback.print_exc()
                
                # 输出所有元数据
                print(f"\n所有元数据:")
                for key, value in img.info.items():
                    print(f"  {key}:")
                    value_str = str(value)
                    if len(value_str) > 300:
                        print(f"    类型: {type(value)}")
                        print(f"    长度: {len(value_str)}")
                        print(f"    字符: {value_str}...")
                    else:
                        print(f"    {value_str}")
        
    except Exception as e:
        print(f"错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    debug_workflow()
